# -*- coding: cp866 -*-
import datetime
import time

TIME_FORMAT_MAGIC = '%d%m%Y_%H%M%S'

MS_MSGID_TO_CONTACTID = {
    '11':'1103',
    '13':'1103',
    '20':'1101',
    '22':'1101'
}
MS_BOLID_TO_CONTACTID = {
    'ВЗЛОМКОРПУСА':'3831',
    'ВОССТ.КОРПУСА':'3833',
    'ПОЖ':'1101',
    'ПОЖАР':'1101',
    'СБРОСТРЕВОГИШС':'1103',
    'ВНИМАНИЕ':'1181',
    'ТРЕВОГА':'1231',
    'ТИХАЯТРЕВОГА':'1221',
    'ТРЕВОГАВХОДА':'1341',
    'ИЗМ.ДАТЫ':'6253',
    'ВЗЯТШС':'4003',
    'СНЯТШС':'4011',
    'ПРОГРАММИРОВАНИЕ':'6271',
    'СБРОСПРИБОРА':'3051',
    'ОБР':'3311',
    'КЗ':'3321',
    'АВПИТ':'3011',
    'ВОССТ':'3013',
    'ОБРЫВШС':'3311',
    'РАЗДЕЛВЗЯТ':'4023',
    'РАЗДЕЛСНЯТ':'4021',
    'КОРОТКОЕЗАМЫКАН':'3321',
    'ИДЕНТИФИКАЦИЯХО':'4221',
    'КЗВЫХОДА':'3201',
    'ОБРЫВВЫХОДА':'3201',
    'НЕИСПР.ТЕЛ.ЛИНИИ':'3501',
    'НЕИЗ.СОБЫТИЕ091':'3503',
    'ВЫКЛ.ПРИНТЕРА':'3361',
    'ВКЛ.ПРИНТЕРА':'3363',
    'ИЗМ.ВРЕМЕНИ':'6253'
}



class Event:
    def __init__(self):
        self.eventId    = 0
        self.objectId   = 0
        self.eventReceiveTime   = datetime.datetime.fromtimestamp(time.time())
        self.eventGenerateTime  = self.eventReceiveTime

        self.isWrittenToPCNMySQL        = False
        self.isWrittenToPCNFB           = False
        self.isWrittenToCOMSecurithor   = False
        self.isWrittenToWEBUIStatic     = False

        self.pgsmType       = 0

        self.contactIdOrig  = ''
        self.contactIdFull  = self.contactIdOrig
        self.contactIdType  = ''
        self.contactIdCode  = ''
        self.contactIdZona  = ''
        self.contactIdGroup = ''

        self.gpsLatitude    = 0.0
        self.gpsLongitude   = 0.0
        self.gpsSpeed       = 0.0

    def __cmp__(self, y):
        if y == None:
            return 1
        if self.eventGenerateTime > y.eventGenerateTime:
            return 1
        if self.eventGenerateTime < y.eventGenerateTime:
            return -1
        if self.eventId > y.eventId:
            return 1
        if self.eventId < y.eventId:
            return -1
        return 0


    def fromPGSM(self, rawEvent):
        global MS_MSGID_TO_CONTACTID
        global TIME_FORMAT_MAGIC
        if rawEvent.has_key('id'):          self.eventId    = rawEvent['id']
        if rawEvent.has_key('devid'):       self.objectId   = rawEvent['devid']
        self.pgsmType           = rawEvent['type']
        self.contactIdType      = MS_MSGID_TO_CONTACTID.get(rawEvent['type'], '0000')
        self.eventGenerateTime  = datetime.datetime.strptime(rawEvent['datetime'], TIME_FORMAT_MAGIC)

        self.contactIdZona  = '099'
        self.contactIdGroup = '00'
        cidetype    = self.contactIdType[3]
        cidtype     = self.contactIdType[0:3]
        cidobj      = str(self.objectId)
        while len(cidobj) < 4: cidobj = '0' + cidobj
        self.contactIdFull = '18' + cidobj + cidetype + cidtype + self.contactIdGroup + self.contactIdZona + '0'
        self.contactIdOrig = self.contactIdFull
        return True

    def fromContactId(self, rawEvent):
        global TIME_FORMAT_MAGIC
        if rawEvent.has_key('eventid'):     self.eventid    = rawEvent['eventid']
        cid = rawEvent['value']
        self.contactIdOrig = cid
        self.objectId = cid[0:4]
        cidetype    = cid[6:7]
        cidtype     = cid[7:10]
        self.contactIdType  = '%s%s' % (cidtype, cidetype)
        self.contactIdGroup = cid[10:12]
        self.contactIdZona  = cid[12:15]
        self.contactIdFull = '18' + self.objectId + cidetype + cidtype + self.contactIdGroup + self.contactIdZona + '0'
        self.objectId = str(int(self.objectId))
        self.eventGenerateTime  = datetime.datetime.strptime(rawEvent['date'], TIME_FORMAT_MAGIC)

    def fromBolid(self, rawEvent):
        global TIME_FORMAT_MAGIC

        rawParsed   = str(rawEvent['type']).split('|')
        rawType     = rawParsed[2].replace(' ', '').decode('cp866').encode('u8')
        rawZone     = rawParsed[3].replace(' ', '')
        rawZone     = rawZone.split('/')
        if len(rawZone) == 2: self.contactIdZona = str(rawZone[1])
        if len(self.contactIdZona) < 3: self.contactIdZona = '0' + self.contactIdZona
        rawGroup    = rawParsed[4].replace(' ', '')
        if len(rawGroup) > 0: self.contactIdGroup = str(rawGroup)
        if len(self.contactIdGroup) < 2: self.contactIdGroup = '0' + self.contactIdGroup

        self.contactIdType = MS_BOLID_TO_CONTACTID.get(str(rawType), '0000')
        if self.contactIdType == '0000':
            raise Exception('unknown Bolid type %s' % (str(rawType)))
        self.eventGenerateTime  = datetime.datetime.strptime(rawEvent['datetime'], TIME_FORMAT_MAGIC)

    def fromGPSPoint(self, rawEvent):
        #we should transfer LAT and LON
        #LAT
        ddd = float(rawEvent['lat'])
        self.GPSLatitudeOrig = ddd
        dd = int(ddd)
        mm = int((ddd - dd)*60)
        ss = str(((ddd - dd)*60 - mm)*60)
        mm = str(mm)
        if (len(mm)) < 2:
            mm = '0%s' % (mm[0])
        dd = str(dd)
        self.GPSLatitude = dd[0:2] + mm[0:2] + '.' + ss.replace('.','')[0:5]
        #LON
        ddd = float(rawEvent['lon'])
        self.GPSLongitudeOrig = ddd
        dd = int(ddd)
        mm = int((ddd - dd)*60)
        ss = str(((ddd - dd)*60 - mm)*60)
        mm = str(mm)
        if (len(mm)) < 2:
            mm = '0%s' % (mm[0])
        dd = str(dd)
        self.GPSLongitude = dd[0:2] + mm[0:2] + '.' + ss.replace('.','')[0:5]
        self.GPSSpeed = rawEvent['speed']
        self.eventGenerateTime = datetime.datetime.strptime(rawEvent['date'], TIME_FORMAT_MAGIC)
        if rawEvent.has_key('eventid'):     self.eventid    = rawEvent['eventid']
        if rawEvent.has_key('devid'):       self.objectId   = rawEvent['devid']
